<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\ProjectHire;
use App\Models\SafePlan;
use App\Models\SafePlanOrder;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class SafePlanController extends Controller
{
    public function show(Request $request, $id) {
        $node = SafePlan::findOrFail($id);
        $data = $node->toArray();
        return $this->returnJSON($data, 0, 'ok');
    }

    public function index(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = SafePlan::query();

        //列表按id倒排
        $query->orderBy('id', 'desc');
        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function store(Request $request) {
        if ($request->has('id')) {
            return $this->update($request, $request->get('id'));
        }

        $this->validate($request, [
            'price' => 'required',
            'name' => 'required|max:255',
            'photo' => 'required|max:255',
            'company' => 'required|max:255',
            'description' => 'required|max:255',
            'detail_link' => 'required|max:1024',
            'api' => 'required|max:1024',
            'code' => 'required|max:32',
            'feedback_api' => 'max:1024'
        ]);

        $node = new SafePlan();
        $data = $request->only([
            'price',
            'name',
            'photo',
            'company',
            'description',
            'detail_link',
            'api',
            'status',
            'code',
            'feedback_api'
        ]);

        $data = $this->rmNullProps($data);
        $node->fill($data);

        if ($node->save()) {
            $data = $node->toArray();
            return $this->returnJSON($data, 0, '新增成功');
        }
        return $this->returnJSON(null, 500, '新建失败');
    }

    public function update(Request $request, $id) {
        $node = SafePlan::findOrFail($id);

        $this->validate($request, [
            'price' => 'required',
            'name' => 'required|max:255',
            'photo' => 'required|max:255',
            'company' => 'required|max:255',
            'description' => 'required|max:255',
            'detail_link' => 'required|max:1024',
            'api' => 'required|max:1024',
            'code' => 'required|max:32',
            'feedback_api' => 'max:1024'
        ]);

        $data = $request->only([
            'price',
            'name',
            'photo',
            'company',
            'description',
            'detail_link',
            'api',
            'status',
            'code',
            'feedback_api'
        ]);
        $data = $this->rmNullProps($data);

        $node->fill($data);
        if ($node->save()) {
            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }


    public function online(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = SafePlan::whereIn('id',  $ids)->update(['status' => 1]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '上架成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }
    public function offline(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = SafePlan::whereIn('id',  $ids)->update(['status' => 0]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '下架成功');
        } else {
            return $this->returnJSON(null, 1, "操作失败");
        }
    }

    public function destroy(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        if (SafePlan::whereRaw('id IN (?)', [$ids])->delete()) {
            return $this->returnJSON($ids, 0, '删除成功');
        } else {
            return $this->returnJSON(null, 1, "删除失败");
        }
    }

    public function order(Request $request) {
        $perPage = $request->get('perPage', 10);
        $query = SafePlanOrder::query();

        if($request->get('keyword'))
        {
            $keyword = $request->get('keyword');

            $query->where(function($query) use ($keyword){
               $query->where('name', 'like', "%$keyword%")->orwhere('id_card', 'like', "%$keyword%")->orwhere('insurance_no', 'like', "%$keyword%");
            });
        }
        //列表按id倒排
        $query->orderBy('id', 'desc');
        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function plans(Request $request) {
        $query = SafePlan::query();

        //列表按id倒排
        $query->where('status', '=', '1');
        $query->orderBy('price', 'asc');

        return $this->returnJSON([
            'plans' => $query->get()->toArray()
        ]);
    }

    public function projects(Request $request) {
        $query = Project::query();
        $query->where('verify_status', '=', 1);
        $query->where('status', '=', 1);
        // 从招募时间开始算，因为没有招募开始时间，所以就开始了
        // $query->where('begin', '<', date('Y-m-d H:i:s'));
        $query->where('end', '>', date('Y-m-d H:i:s'));

        $user = $request->user();

        if ($user->type == 3) {
            $query->where('org_id', '=', $user->org_id);
        } else if ($user->type == 2) {
            $teamIds = [$user->team_id];
//            foreach (Team::whereDescendantOf($user->team)->select('id')->get()->toArray() as $item) {
//                $teamIds[] = $item['id'];
//            }
            $query->whereIn('team_id', $teamIds);
        } else if ($user->type == 4 && $request->has('org_id')) {
            $query->where('org_id', '=', $request->get('org_id'));
        }

        $query->orderBy('recommend_time', 'desc');
        $query->orderBy('publish_time', 'desc');
        $query->orderBy('id', 'desc');

        return $this->returnJSON([
            'options' => array_map(function($item) {
                return [
                    'label' => $item['name'],
                    'value' => $item['id']
                ];
            }, $query->get()->toArray())
        ]);
    }

    public function buySafe(Request $request, $id) {
        $project = null;
        if (intval($id)) {
            $project = Project::find($id);
        }

        $user = $request->user();
        $team = null;

        if ($project && $project->team) {
            $team = $project->team;
        } else if ($user->type == 2) {
            $team = $user->team;
        }


        $data = [];
        $data['token'] = '123456';
        //$data['m_type'] = $id == 0 ? '1' : '2';
        $data['activity_id'] = 'none';

        if ($project) {
            $data['activity_id'] = $project->id;
            $data['activity_name'] = $project->name;
            $data['activity_code'] = $project->identifier;
            $data['volunteer_type'] = 2;
            $data['project_id'] = $project->id;
        }

        if ($request->get('m_type', 0) == 1 && $team) {
            $data['m_name'] = $team->legal_person;
            $data['m_cardno'] = $team->legal_person_id;
            $data['m_mobile'] = $team->contact_phone;
            $data['m_email'] = $team->contact_email;
        }

        if ($request->has('import_file')) {
            $file = public_path($request->get('import_file'));
            if (!file_exists($file)) {
                throw new \Exception('文件上传出错');
            }

            $reader = Excel::load($file);
            $volunteers = $error = [];
            foreach ($reader->toArray() as $row) {
                $item = [];
                $item = [
                    'c_name' => isset($row['姓名']) ? $row['姓名'] : '',
                    'c_mobile' => isset($row['手机']) && !empty($row['手机']) ? intval($row['手机']) : (isset($row['联系电话']) && !empty($row['联系电话']) ? intval($row['联系电话']) : ''),
                    'c_cardno' => isset($row['身份证号']) ? strval(intval($row['身份证号'])) : ''
                ];

                if(strlen($item['c_cardno']) == 17)
                {
                    $item['c_cardno'] = $item['c_cardno']."X";
                }
                if (
                    empty($item['c_name'])
                    || empty($item['c_mobile'])
                    || empty($item['c_cardno'])
                ) {
                    $item['msg'] = '关键字断不能为空';
                    $error[] = $item;
                    continue;
                }
                if (!preg_match('#^\d{11}$#', $item['c_mobile'])) {
                    $item['msg'] = '手机号码格式错误';
                    $error[] = $item;
                    continue;
                }/* else if (!checkIdCard($item['c_cardno'])) {
                    continue;
                }*/
                $volunteers[] = $item;
            }
            $data['volunteers'] = $volunteers;
            $data['error'] = $error;
        } else if ($project) {
            $query = ProjectHire::with(['user.volunteer'])->where('project_id', '=', $id);
            $query->where('verify_status', '=', 1);
            $hires = $query->get()->toArray();
            $volunteers = [];

            foreach ($hires as $item) {
                if (!isset($item['user']) || !isset($item['user']['volunteer'])) {
                    continue;
                }

                $volunteer = $item['user']['volunteer'];


                $volunteers[] = [
                    'c_name' => !empty($volunteer['real_name']) ? $volunteer['real_name'] : $item['user']['username'],
                    'c_cardno' => $volunteer['id_number'],
                    'c_mobile' => $volunteer['phone'],
                ];
            }
            $data['volunteers'] = $volunteers;
        }


        return $this->returnJSON($data, 0, 'ok');
    }
}
